<template>
    <div>
        <el-dialog title="操作选项" :visible.sync="dialogVisible" width="30%" @close="dialogVisible = false">
            <el-button type="primary" @click="dialogVisible1 = true">修改密码</el-button>
            <el-button type="danger" v-if="this.userInfo.isRemember===1" @click="handleResetPassword">重置密码</el-button>
            <el-button type="warning" v-if="this.userInfo.isAction===1" @click="banUser">封禁</el-button>
            <el-button type="success" v-else-if="this.userInfo.isAction===0" @click="unbanUser">解禁</el-button>
            <el-button @click="dialogVisible = false">取消</el-button>
        </el-dialog>
        <!--
                <el-dialog title="修改密码" :visible.sync="dialogVisible1" width="30%">
                    <el-form :model="form" ref="form" :rules="rules" label-width="80px">
                        <el-form-item label="旧密码" prop="oldPassword">
                            <el-input v-model="form.oldPassword" show-password type="password"></el-input>
                        </el-form-item>
                        <el-form-item label="新密码" prop="newPassword">
                            <el-input v-model="form.newPassword" show-password type="password"></el-input>
                        </el-form-item>
                        <el-form-item label="确认密码" prop="confirmPassword">
                            <el-input v-model="form.confirmPassword" show-password type="password"></el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="submitForm">提交</el-button>
                            <el-button @click="dialogVisible1 = false">取消</el-button>
                        </el-form-item>
                    </el-form>
                </el-dialog>
        -->


        <!--主体内容-->
        <el-col :span="6">
            <el-input v-model="queryFrom.username" placeholder="请输入搜索内容" @input="handleSearch"></el-input>
        </el-col>
        <el-col :span="2">
            <el-button type="primary" @click="handleSearch">搜索</el-button>
        </el-col>

        <el-table ref="formData" :data="formData"
                  :cell-style="{'text-align':'center'}" :header-cell-style="{'text-align':'center'}">
            <el-table-column prop="username" label="账号" fixed="left"></el-table-column>
            <el-table-column label="状态" width="100">
                <template slot-scope="scope">
                    <el-button v-if="scope.row.status==0" @click="handleSetStatus(scope.row)" type="success" size="small"
                               plain>未禁用
                    </el-button>
                    <el-button v-else-if="scope.row.status==1" @click="handleSetStatus(scope.row)" type="info"
                               size="small" plain>已禁用
                    </el-button>
                </template>
            </el-table-column>
            <el-table-column prop="name" label="名称"></el-table-column>
            <el-table-column label="身份">
                <template slot-scope="scope">
                    <el-tag type="danger" v-if="scope.row.role===2">超管</el-tag>
                    <el-tag v-else-if="scope.row.role==='USER'">用户</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="密码" width="100">
                <template slot-scope="scope">
                    <el-button type="warning" size="small" @click="handleResetPassword(scope.row)" plain>重置密码
                    </el-button>
                </template>
            </el-table-column>
            <el-table-column prop="email" label="用户邮箱" width="200"></el-table-column>
            <el-table-column prop="phone" label="手机号码" width="200"></el-table-column>
            <el-table-column prop="registerDate" label="注册时间" width="180"></el-table-column>
            <el-table-column prop="loginDate" label="上一次登录时间" width="180"></el-table-column>
            <el-table-column label="操作" width="120" fixed="right">
                <template slot-scope="scope">
                    <!--
                                        <el-button v-if="scope.row.userName !== 'root'" @click="handleEdit(scope.$index, scope.row)"
                                                   type="primary" size="small">编辑
                                        </el-button>
                    -->
                    <el-button v-if="scope.row.userName !== 'root'" @click="handleDelete(scope.row)"
                               type="danger" size="small">删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- Element UI分页器 -->
        <div class="contact-list-page">
            <el-pagination v-if="formData.length!==0"
                           @size-change="handleSizeChange"
                           @current-change="handleCurrentChange"
                           :current-page="queryFrom.current"
                           :page-sizes="[10, 30, 50, 100]"
                           :page-size="queryFrom.size"
                           layout="total, sizes, prev, pager, next, jumper"
                           :total="queryFrom.total">
            </el-pagination>
        </div>
    </div>
</template>
<script>
import axios from "axios";

export default {
    data() {
        var validateOldPass = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请再次输入密码'));
            } else if (value !== this.userInfo.userPass) {
                callback(new Error('旧密码输入错误!'));
            } else {
                callback();
            }
        };
        var validatePass = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请再次输入密码'));
            } else if (value !== this.form.newPassword) {
                callback(new Error('两次输入的密码不一致!'));
            } else {
                callback();
            }
        };
        return {
            // 列表查询条件。
            queryFrom: {
                // userId: null,
                // username: "",
                // name: "",
                // password: "",
                // // role: "student",
                // email: "",
                // phone: "",
                // classId: null,
                // className: ""

                username: null,

                total: 0,
                size: 10,
                current: 1,
                pages: 1,
            },
            // 数据部分。
            formData: [],
            userInfo: {
                userId: '',
                userName: '',
                userPass: ''
            },
            // 多选。
            multipleSelection: [],
            userList: [], // 用户列表
            currentPage: 1, // 当前页码
            pageSize: 10, // 每页显示数量
            total: 0, // 总数
            unreadEmails: 0, // 总邮件数
            drag: false,
            dialogVisible: false,
            dialogVisible1: false,
            form: {
                oldPassword: '',
                newPassword: '',
                confirmPassword: '',
            },
            rules: {
                oldPassword: [
                    {required: true, message: '请输入旧密码', trigger: 'blur'},
                    {validator: validateOldPass, trigger: ['blur', 'change']}
                ],
                newPassword: [
                    {required: true, message: '请输入新密码', trigger: 'blur'},
                ],
                confirmPassword: [
                    {required: true, message: '请再次输入新密码', trigger: 'blur'},
                    {validator: validatePass, trigger: ['blur', 'change']}
                ],
            }
        };
    },
    watch: {
        searchUser(newVal, oldVal) {
            // 当 searchUser 发生变化时，调用 getUserList 方法
            if (newVal !== oldVal) {
                this.getUserList();
                this.getUserPage();
            }
        }

    },
    created() {
        this.getUserPage();
    },
    methods: {
        getUserPage() {
            console.log("this.queryFrom ===========>  ", this.queryFrom);
            // 获取用户列表
            this.$store.dispatch('getUserInfoPage', this.queryFrom).then(res => {
                // console.log("getContactPage =======> res.data =====>", res);
                if (res !== undefined && res.resultStatus === true) {
                    // console.log("res.resultData", res.resultData);
                    // console.log("res.resultData", res.resultData.records);
                    // this.$message.success(res.resultData);
                    this.formData = res.resultData.records
                    this.queryFrom.total = res.resultData.total
                    this.queryFrom.size = res.resultData.size
                    this.queryFrom.current = res.resultData.current
                    this.queryFrom.pages = res.resultData.pages
                } else if (res !== undefined && res.resultStatus === false) {
                    // console.log("res.resultData", res.resultData);
                    this.$message.error(res.errorMessage);
                }
            }).catch(res => {
                this.$message.error("后台出问题啦！程序猿小哥正在紧急修复中！！！");
            });
        },
        getUserList() {
        },
        handleSizeChange(val) {
            // console.log(`每页 ${val} 条`);
            this.queryFrom.size = val
            this.getUserPage()
        },
        handleCurrentChange(val) {
            // console.log(`当前页: ${val}`);
            this.queryFrom.current = val
            this.getUserPage()
        },

        // handleSelectionChange(val) {
        //     this.multipleSelection = val;
        // },
        handleSearch() {
            this.getUserPage();
        },

        // 点击了删除按钮。
        handleDelete(row) {
            console.log(row)
            this.userInfo.userId = row.userId;
            this.userInfo.userName = row.userName;
            this.userInfo.userPass = row.userPass;
            this.$confirm('此操作将删除该用户及邮箱, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.deleteUser(row);
                this.userInfo = {
                    userId: '',
                    userName: '',
                    userPass: ''
                };
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        handleEdit(index, row) {
            this.userInfo.userId = row.userId;
            this.userInfo.userName = row.userName;
            this.userInfo.userPass = row.userPass;
            this.userInfo.isAction = row.isAction;
            this.userInfo.isRemember = row.isRemember;

            this.dialogVisible = true;
        },
        submitForm() {
            console.log("提交")
            this.$refs.form.validate((valid) => {
                if (valid) {
                    this.changePassword();
                    this.userInfo = {
                        userId: '',
                        userName: '',
                        userPass: '',
                        isAction: '',
                        isRemember: '',
                    };
                    this.$router.push('/user')
                }
            });
        },
        // 修改密码
        changePassword() {
            console.log(this.userInfo.userId);
            axios.post('http://localhost:8989/user/changePassword', {
                userId: this.userInfo.userId,
                userName: this.userInfo.userName,
                userPass: this.form.newPassword,
            }).then((response) => {
                console.log(response.data);
                this.dialogVisible1 = false;
                this.dialogVisible = false;
                this.$message({
                    message: '修改成功',
                    type: 'success'
                });

            }).catch((error) => {
                this.$message({
                    message: '修改失败',
                    type: 'error'
                });
            })

        },
        // 点击了重置密码按钮。
        handleResetPassword(row) {
            console.log("row =========> ", row)
            this.$confirm('此操作将 重置 用户【' + row.username + '】的密码, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.resetPassword(row);
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        // 重置密码。
        resetPassword(row) {
            this.$store.dispatch('resetPassword', row.userId).then(res => {
                // console.log("getContactPage =======> res.data =====>", res);
                if (res !== undefined && res.resultStatus === true) {
                    // console.log("res.resultData", res.resultData);
                    // console.log("res.resultData", res.resultData.records);
                    this.$message.success(res.resultData);
                } else if (res !== undefined && res.resultStatus === false) {
                    // console.log("res.resultData", res.resultData);
                    this.$message.error(res.errorMessage);
                }
            }).catch(res => {
                this.$message.error("后台出问题啦！程序猿小哥正在紧急修复中！！！");
            });


            // console.log(this.userInfo.userId);
            // axios.post('http://localhost:8989/user/changePassword', {
            //     userId: this.userInfo.userId,
            //     userName: this.userInfo.userName,
            //     userPass: "123456",
            // }).then((response) => {
            //     console.log(response.data);
            //     this.dialogVisible = false;
            //     this.reset();
            // }).catch((error) => {
            //     this.$message({
            //         message: '重置失败',
            //         type: 'error'
            //     })
            // })
        },
        // 点击了设置用户状态按钮。
        handleSetStatus(row) {
            this.$confirm('此操作将 禁用 用户【' + row.username + '】, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.setStatus(row);
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        // 设置用户状态。
        setStatus(row) {
            this.$store.dispatch('setStatus', row.userId).then(res => {
                // console.log("getContactPage =======> res.data =====>", res);
                if (res !== undefined && res.resultStatus === true) {
                    // console.log("res.resultData", res.resultData);
                    // console.log("res.resultData", res.resultData.records);
                    this.$message.success(res.resultData);
                    this.getUserPage();
                } else if (res !== undefined && res.resultStatus === false) {
                    // console.log("res.resultData", res.resultData);
                    this.$message.error(res.errorMessage);
                }
            }).catch(res => {
                this.$message.error("后台出问题啦！程序猿小哥正在紧急修复中！！！");
            });

        },
        reset() {
            axios.post('http://localhost:8989/user/resetPassword', {
                userId: this.userInfo.userId,
                userName: this.userInfo.userName,
            }).then((response) => {
                console.log(response.data);
                this.$router.go(0)
                this.$message({
                    message: '重置成功',
                    type: 'success'
                });
            }).catch((error) => {
                this.$message({
                    message: '重置失败',
                    type: 'error'
                })
            })
        },
        logout() {
            this.$confirm('此操作将退出账号, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$store.commit('logout');
                this.$router.push({path: '/'});
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
        },
        banUser() {
            this.$confirm('此操作将封禁账号, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                axios.post('http://localhost:8989/user/banUser', {
                    userId: this.userInfo.userId,
                    userName: this.userInfo.userName,
                }).then((response) => {
                    console.log(response.data);
                    this.$router.go(0)
                    this.$message({
                        message: '封禁成功',
                        type: 'success'
                    });
                }).catch((error) => {
                    this.$message({
                        message: '封禁失败',
                    })
                })
            });
        },
        unbanUser() {
            this.$confirm('此操作将解封账号, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                axios.post('http://localhost:8989/user/unBanUser', {
                    userId: this.userInfo.userId,
                    userName: this.userInfo.userName,
                }).then((response) => {
                    console.log(response.data);
                    this.dialogVisible = false;
                    this.$router.go(0)
                    this.$message({
                        message: '解封成功',
                        type: 'success'
                    });
                }).catch((error) => {
                    this.$message({
                        message: '解封失败',
                    })
                })
            })
        },

        // 删除用户。
        deleteUser(row) {
            this.$confirm('此操作将注销账号, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                console.log("deleteUser");
                console.log("row.userId ========> ", row.userId);
                this.$store.dispatch('deleteUserInfo', row.userId).then(res => {
                    // console.log("getContactPage =======> res.data =====>", res);
                    if (res !== undefined && res.resultStatus === true) {
                        // console.log("res.resultData", res.resultData);
                        // console.log("res.resultData", res.resultData.records);
                        // this.$message.success(res.resultData);
                        this.formData = res.resultData.records
                        this.queryFrom.total = res.resultData.total
                        this.queryFrom.size = res.resultData.size
                        this.queryFrom.current = res.resultData.current
                        this.queryFrom.pages = res.resultData.pages
                    } else if (res !== undefined && res.resultStatus === false) {
                        // console.log("res.resultData", res.resultData);
                        this.$message.error(res.errorMessage);
                    }
                }).catch(res => {
                    this.$message.error("后台出问题啦！程序猿小哥正在紧急修复中！！！");
                });
                // axios.post('http://localhost:8989/user/deleteUser', {
                //     userId: this.userInfo.userId,
                //     userName: this.userInfo.userName,
                //     userPass: this.userInfo.userPass,
                // }).then(res => {
                //     this.$message({
                //         type: 'success',
                //         message: '注销成功!'
                //     });
                //     this.$router.go(0)
                // }).catch(res => {
                //     this.$message({
                //         type: 'error',
                //         message: '注销失败!'
                //     });
                // });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
        },
    }
}
</script>
<style scoped>
.contact-list-page {
    text-align: center;
    margin-top: 8vh;;
}
</style>